Option Strict On
Option Explicit On
'Copyright (c) 2007-2010, William Severance, Jr., WESNet Designs
'All rights reserved.

'Redistribution and use in source and binary forms, with or without modification, are permitted
'provided that the following conditions are met:

'Redistributions of source code must retain the above copyright notice, this list of conditions
'and the following disclaimer.

'Redistributions in binary form must reproduce the above copyright notice, this list of conditions
'and the following disclaimer in the documentation and/or other materials provided with the distribution.

'Neither the name of William Severance, Jr. or WESNet Designs may be used to endorse or promote
'products derived from this software without specific prior written permission.

'Disclaimer: THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
'            OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
'            AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER BE LIABLE
'            FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
'            LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
'            INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
'            OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
'            IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

'Although I will try to answer questions regarding the installation and use of this software when
'such questions are submitted via e-mail to the below address, no promise of further
'support or enhancement is made nor should be assumed.

'Developer Contact Information:
'     William Severance, Jr.
'     WESNet Designs
'     679 Upper Ridge Road
'     Bridgton, ME 04009
'     Phone: 207-647-9375
'     E-Mail: bill@wesnetdesigns.com
'     Website: www.wesnetdesigns.com
'
Imports System.Reflection

Namespace WESNet.DNN.Modules.EPrayer
    Partial Class ListEditor
        Inherits DotNetNuke.Framework.UserControlBase

        Private _ModuleId As Integer = -1
        Private _LocalResourceFile As String

        Public Property ListName() As String
            Get
                Return CType(ViewState("ListName"), String)
            End Get
            Set(ByVal value As String)
                ViewState("ListName") = value
            End Set
        End Property

        Public Property ShowRowNumbers() As Boolean
            Get
                If ViewState("ShowRowNumbers") Is Nothing Then
                    Return True
                Else
                    Return CType(ViewState("ShowRowNumbers"), Boolean)
                End If
            End Get
            Set(ByVal value As Boolean)
                ViewState("ShowRowNumbers") = value
            End Set
        End Property

        Public ReadOnly Property ModuleId() As Integer
            Get
                If _ModuleId = Null.NullInteger Then
                    _ModuleId = GetModuleId(Me)
                End If
                Return _ModuleId
            End Get
        End Property

        Public ReadOnly Property LocalResourceFile() As String
            Get
                If _LocalResourceFile Is Nothing Then
                    _LocalResourceFile = GetLocalResourceFile(Me)
                End If
                Return _LocalResourceFile
            End Get
        End Property

        Private Function GetModuleId(ByVal ctl As Control) As Integer
            If ctl Is Nothing Then
                Return -1
            Else
                Dim mid As Integer = -1
                Dim Parent As Control = ctl.Parent
                If Not Parent Is Nothing Then
                    If TypeOf Parent Is DotNetNuke.Entities.Modules.ModuleSettingsBase Then
                        mid = DirectCast(Parent, DotNetNuke.Entities.Modules.ModuleSettingsBase).ModuleId
                    ElseIf TypeOf Parent Is DotNetNuke.Entities.Modules.PortalModuleBase Then
                        mid = DirectCast(Parent, DotNetNuke.Entities.Modules.PortalModuleBase).ModuleId
                    Else
                        Dim pi As System.Reflection.PropertyInfo = Parent.GetType.GetProperty("ModuleId")
                        If Not pi Is Nothing Then
                            'If Parent has a ModuleId property use this
                            mid = CType(pi.GetValue(Parent, Nothing), Integer)
                        Else
                            'Otherwise, look further up the control hierarchy
                            mid = GetModuleId(Parent)
                        End If
                    End If
                End If
                Return mid
            End If
        End Function

        Private Function GetLocalResourceFile(ByVal ctl As Control) As String

            If ctl Is Nothing Then
                Return Me.TemplateSourceDirectory & "/App_LocalResources/ListEditor.ascx.resx"
            Else
                Dim LocalResourceFile As String = String.Empty
                Dim Parent As Control = ctl.Parent
                If Not Parent Is Nothing Then
                    If TypeOf Parent Is DotNetNuke.Entities.Modules.ModuleSettingsBase Then
                        LocalResourceFile = DirectCast(Parent, DotNetNuke.Entities.Modules.ModuleSettingsBase).LocalResourceFile
                    ElseIf TypeOf Parent Is DotNetNuke.Entities.Modules.PortalModuleBase Then
                        LocalResourceFile = DirectCast(Parent, DotNetNuke.Entities.Modules.PortalModuleBase).LocalResourceFile
                    Else
                        Dim pi As System.Reflection.PropertyInfo = Parent.GetType.GetProperty("LocalResourceFile")
                        If Not pi Is Nothing Then
                            'If Parent has a LocalResourceFile property use it
                            LocalResourceFile = CType(pi.GetValue(Parent, Nothing), String)
                        Else
                            'Otherwise, look further up the control hierarchy
                            LocalResourceFile = GetLocalResourceFile(Parent)
                        End If
                    End If
                End If
                Return LocalResourceFile
            End If
        End Function

        Private Sub BindList()
            Dim epc As New EPrayerController
            Select Case ListName
                Case "Categories"
                    With gvList
                        .DataKeyNames = New String() {"CategoryID", "ViewOrder"}
                        Dim categories As List(Of CategoryInfo) = epc.GetCategories(ModuleId)
                        If .EditIndex >= gvList.Rows.Count Then
                            Dim objCategoryInfo As New CategoryInfo
                            objCategoryInfo.ViewOrder = gvList.Rows.Count
                            categories.Add(objCategoryInfo)
                        End If
                        .DataSource = categories
                    End With
                Case "ChurchRelationships"
                    With gvList
                        .DataKeyNames = New String() {"ChurchRelationshipID", "ViewOrder"}
                        Dim churchrelationships As List(Of ChurchRelationshipInfo) = epc.GetChurchRelationships()
                        If .EditIndex >= gvList.Rows.Count Then
                            Dim objChurchRelationshipInfo As New ChurchRelationshipInfo
                            objChurchRelationshipInfo.ViewOrder = gvList.Rows.Count
                            churchrelationships.Add(objChurchRelationshipInfo)
                        End If
                        .DataSource = churchrelationships
                    End With
                Case "Distributions"
                    With gvList
                        .DataKeyNames = New String() {"DistributionID", "ViewOrder"}
                        Dim distributions As List(Of DistributionInfo) = epc.GetDistributions(ModuleId)
                        If .EditIndex >= gvList.Rows.Count Then
                            Dim objDistributionInfo As New DistributionInfo
                            objDistributionInfo.ViewOrder = gvList.Rows.Count
                            distributions.Add(objDistributionInfo)
                        End If
                        .DataSource = distributions
                    End With
                Case "Relationships"
                    With gvList
                        .DataKeyNames = New String() {"RelationshipID", "ViewOrder"}
                        Dim relationships As List(Of RelationshipInfo) = epc.GetRelationships()
                        If .EditIndex >= gvList.Rows.Count Then
                            Dim objRelationshipInfo As New RelationshipInfo
                            objRelationshipInfo.ViewOrder = gvList.Rows.Count
                            relationships.Add(objRelationshipInfo)
                        End If
                        .DataSource = relationships
                    End With
                Case "Stati"
                    With gvList
                        .DataKeyNames = New String() {"StatusID", "ViewOrder"}
                        Dim stati As List(Of StatusInfo) = epc.GetStati()
                        If .EditIndex >= gvList.Rows.Count Then
                            Dim objStatusInfo As New StatusInfo
                            objStatusInfo.ViewOrder = gvList.Rows.Count
                            stati.Add(objStatusInfo)
                        End If
                        .DataSource = stati
                    End With
            End Select
            gvList.DataBind()
            If gvList.Rows.Count > 0 Then gvList.Rows(gvList.Rows.Count - 1).FindControl("btnDown").Visible = False
        End Sub

        Private Sub SaveRow(ByVal row As GridViewRow)
            Dim ViewOrder As Integer = Convert.ToInt32(gvList.DataKeys(row.RowIndex).Values(1))
            SaveRow(row, ViewOrder)
        End Sub

        Private Sub SaveRow(ByVal row As GridViewRow, ByVal ViewOrder As Integer)
            Dim ID As Integer = CType(gvList.DataKeys(row.RowIndex).Value, Integer)
            Dim Name As String
            Dim mid As Integer

            If (row.RowState And DataControlRowState.Edit) <> 0 Then
                Name = CType(row.FindControl("tbName"), TextBox).Text
                If gvList.Columns(3).Visible Then
                    If CType(row.FindControl("cbPortalGlobal"), CheckBox).Checked Then
                        mid = Null.NullInteger
                    Else
                        mid = Me.ModuleId
                    End If
                Else
                    mid = Me.ModuleId
                End If
            Else
                Name = CType(row.FindControl("lblName"), Label).Text
                If gvList.Columns(3).Visible Then
                    If CType(row.FindControl("imgPortalGlobal"), System.Web.UI.WebControls.Image).ImageUrl.EndsWith("/checked.gif") Then
                        mid = Null.NullInteger
                    Else
                        mid = Me.ModuleId
                    End If
                Else
                    mid = Me.ModuleId
                End If
            End If
            Save(ID, Name, mid, ViewOrder)
        End Sub

        Private Sub Save(ByVal ID As Integer, ByVal Name As String, ByVal ModuleID As Integer, ByVal ViewOrder As Integer)
            Dim epc As New EPrayerController
            Select Case ListName
                Case "Categories"
                    Dim objCategoryInfo As New CategoryInfo
                    With objCategoryInfo
                        .ModuleID = ModuleID
                        .CategoryID = ID
                        .Category = Name
                        .ViewOrder = ViewOrder
                    End With
                    If ID = -1 Then
                        epc.AddCategory(objCategoryInfo)
                    Else
                        epc.UpdateCategory(objCategoryInfo)
                    End If

                Case "Distributions"
                    Dim objDistributionInfo As New DistributionInfo
                    With objDistributionInfo
                        .ModuleID = ModuleID
                        .DistributionID = ID
                        .Distribution = Name
                        .ViewOrder = ViewOrder
                    End With
                    If ID = -1 Then
                        epc.AddDistribution(objDistributionInfo)
                    Else
                        epc.UpdateDistribution(objDistributionInfo)
                    End If
                Case "Stati"
                    Dim objStatusInfo As New StatusInfo
                    With objStatusInfo
                        .StatusID = ID
                        .Status = Name
                        .ViewOrder = ViewOrder
                    End With
                    If ID = -1 Then
                        epc.AddStatus(objStatusInfo)
                    Else
                        epc.UpdateStatus(objStatusInfo)
                    End If
                Case "Relationships"
                    Dim objRelationshipInfo As New RelationshipInfo
                    With objRelationshipInfo
                        .RelationshipID = ID
                        .Relationship = Name
                        .ViewOrder = ViewOrder
                    End With
                    If ID = -1 Then
                        epc.AddRelationship(objRelationshipInfo)
                    Else
                        epc.UpdateRelationship(objRelationshipInfo)
                    End If
                Case "ChurchRelationships"
                    Dim objChurchRelationshipInfo As New ChurchRelationshipInfo
                    With objChurchRelationshipInfo
                        .ChurchRelationshipID = ID
                        .ChurchRelationship = Name
                        .ViewOrder = ViewOrder
                    End With
                    If ID = -1 Then
                        epc.AddChurchRelationship(objChurchRelationshipInfo)
                    Else
                        epc.UpdateChurchRelationship(objChurchRelationshipInfo)
                    End If
            End Select
        End Sub

        Protected Sub btnAdd_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAdd.Click
            gvList.EditIndex = gvList.Rows.Count
            BindList()
            btnAdd.Visible = False
        End Sub

        Protected Sub ListEditor_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
            If DotNetNuke.Framework.AJAX.IsInstalled Then
                DotNetNuke.Framework.AJAX.RegisterScriptManager()
                'DotNetNuke.Framework.AJAX.WrapUpdatePanelControl(Me.pnlUpdate, True)
            End If
        End Sub

        Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
            If Not IsPostBack Then
                gvList.Columns(0).Visible = ShowRowNumbers
                Select Case ListName
                    Case "Categories"
                        gvList.Columns(2).HeaderText = Localization.GetString("Category.Header", LocalResourceFile)
                        gvList.Columns(3).Visible = True
                    Case "Distributions"
                        gvList.Columns(2).HeaderText = Localization.GetString("Distribution.Header", LocalResourceFile)
                        gvList.Columns(3).Visible = True
                    Case "Stati"
                        gvList.Columns(2).HeaderText = Localization.GetString("Status.Header", LocalResourceFile)
                        gvList.Columns(3).Visible = False
                    Case "Relationships"
                        gvList.Columns(2).HeaderText = Localization.GetString("Relationship.Header", LocalResourceFile)
                        gvList.Columns(3).Visible = False
                    Case "ChurchRelationships"
                        gvList.Columns(2).HeaderText = Localization.GetString("Church_Relationship.Header", LocalResourceFile)
                        gvList.Columns(3).Visible = False
                End Select
                If gvList.Columns(3).Visible Then gvList.Columns(3).HeaderText = Localization.GetString("Portal_Global.Header", LocalResourceFile)
                BindList()
            End If
        End Sub

        Protected Sub gvList_RowCancelingEdit(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCancelEditEventArgs) Handles gvList.RowCancelingEdit
            gvList.EditIndex = -1
            btnAdd.Visible = True
            BindList()
        End Sub

        Protected Sub gvList_RowCommand(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) Handles gvList.RowCommand
            Dim Idx As Integer = Convert.ToInt32(e.CommandArgument)
            Select Case e.CommandName
                Case "MoveUp"
                    SwapOrder(Idx, Idx - 1)
                Case "MoveDown"
                    SwapOrder(Idx, Idx + 1)
            End Select
        End Sub

        Private Sub SwapOrder(ByVal Idx As Integer, ByVal Idx2 As Integer)
            If Idx2 >= 0 And Idx2 < gvList.DataKeys.Count Then
                Dim ViewOrder1 As Integer = Convert.ToInt32(gvList.DataKeys(Idx).Values(1))
                Dim ViewOrder2 As Integer = Convert.ToInt32(gvList.DataKeys(Idx2).Values(1))
                SaveRow(gvList.Rows(Idx), ViewOrder2)
                SaveRow(gvList.Rows(Idx2), ViewOrder1)
            End If
            BindList()
        End Sub

        Protected Sub gvList_RowCreated(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gvList.RowCreated
            If ShowRowNumbers AndAlso e.Row.RowType = DataControlRowType.DataRow Then
                e.Row.Cells(0).Text = (e.Row.RowIndex + 1).ToString
            End If
        End Sub

        Protected Sub gvList_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles gvList.RowDataBound
            Dim tbName As TextBox = Nothing
            Dim lblName As Label = Nothing
            Dim cbPortalGlobal As CheckBox = Nothing
            Dim imgPortalGlobal As System.Web.UI.WebControls.Image = Nothing

            If e.Row.RowType = DataControlRowType.DataRow Then
                Dim btnUp As ImageButton = CType(e.Row.Cells(4).Controls(1), ImageButton)
                btnUp.CommandArgument = e.Row.RowIndex.ToString
                Dim btnDown As ImageButton = CType(e.Row.Cells(4).Controls(3), ImageButton)
                btnDown.CommandArgument = e.Row.RowIndex.ToString
                If e.Row.RowIndex = 0 Then
                    btnUp.Visible = False
                    btnDown.Style.Add("margin-left", "18px")
                End If

                If (e.Row.RowState And DataControlRowState.Edit) <> 0 Then
                    tbName = CType(e.Row.FindControl("tbName"), TextBox)
                    cbPortalGlobal = CType(e.Row.FindControl("cbPortalGlobal"), CheckBox)
                    btnUp.Visible = False
                    btnDown.Visible = False
                Else
                    lblName = CType(e.Row.FindControl("lblName"), Label)
                    imgPortalGlobal = CType(e.Row.FindControl("imgPortalGlobal"), System.Web.UI.WebControls.Image)
                End If

                Select Case ListName
                    Case "Categories"
                        If (e.Row.RowState And DataControlRowState.Edit) <> 0 Then
                            tbName.Text = CType(e.Row.DataItem, CategoryInfo).Category
                            cbPortalGlobal.Checked = CType(e.Row.DataItem, CategoryInfo).ModuleID = Null.NullInteger
                        Else
                            lblName.Text = CType(e.Row.DataItem, CategoryInfo).Category
                            If CType(e.Row.DataItem, CategoryInfo).ModuleID = -1 Then
                                imgPortalGlobal.ImageUrl = "~/images/checked.gif"
                            Else
                                imgPortalGlobal.ImageUrl = "~/images/unchecked.gif"
                            End If
                        End If
                    Case "Distributions"
                        If (e.Row.RowState And DataControlRowState.Edit) <> 0 Then
                            tbName.Text = CType(e.Row.DataItem, DistributionInfo).Distribution
                            cbPortalGlobal.Checked = CType(e.Row.DataItem, DistributionInfo).ModuleID = Null.NullInteger
                        Else
                            lblName.Text = CType(e.Row.DataItem, DistributionInfo).Distribution
                            If CType(e.Row.DataItem, DistributionInfo).ModuleID = -1 Then
                                imgPortalGlobal.ImageUrl = "~/images/checked.gif"
                            Else
                                imgPortalGlobal.ImageUrl = "~/images/unchecked.gif"
                            End If
                        End If
                    Case "Stati"
                        If (e.Row.RowState And DataControlRowState.Edit) <> 0 Then
                            tbName.Text = CType(e.Row.DataItem, StatusInfo).Status
                        Else
                            lblName.Text = CType(e.Row.DataItem, StatusInfo).Status
                        End If
                    Case "Relationships"
                        If (e.Row.RowState And DataControlRowState.Edit) <> 0 Then
                            tbName.Text = CType(e.Row.DataItem, RelationshipInfo).Relationship
                        Else
                            lblName.Text = CType(e.Row.DataItem, RelationshipInfo).Relationship
                        End If
                    Case "ChurchRelationships"
                        If (e.Row.RowState And DataControlRowState.Edit) <> 0 Then
                            tbName.Text = CType(e.Row.DataItem, ChurchRelationshipInfo).ChurchRelationship
                        Else
                            lblName.Text = CType(e.Row.DataItem, ChurchRelationshipInfo).ChurchRelationship
                        End If
                End Select
            End If
        End Sub

        Protected Sub gvList_RowDeleting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewDeleteEventArgs) Handles gvList.RowDeleting
            Dim ID As Integer = CInt(gvList.DataKeys(e.RowIndex).Value)
            Dim epc As New EPrayerController
            Select Case ListName
                Case "Categories"
                    epc.DeleteCategory(ID)
                Case "Distributions"
                    epc.DeleteDistribution(ID)
                Case "Stati"
                    epc.DeleteStatus(ID)
                Case "Relationships"
                    epc.DeleteRelationship(ID)
                Case "ChurchRelationships"
                    epc.DeleteChurchRelationship(ID)
            End Select
            BindList()
        End Sub

        Protected Sub gvList_RowEditing(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewEditEventArgs) Handles gvList.RowEditing
            gvList.EditIndex = e.NewEditIndex
            btnAdd.Visible = False
            BindList()
        End Sub

        Protected Sub gvList_RowUpdating(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewUpdateEventArgs) Handles gvList.RowUpdating
            SaveRow(gvList.Rows(e.RowIndex))
            gvList.EditIndex = -1
            btnAdd.Visible = True
            BindList()
        End Sub
    End Class
End Namespace
